package com.example.spring.boot.rabbitmq.configure;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class RabbitDeadQueueListener {

    @RabbitListener(queues = {"stockQ"}, containerFactory = "rabbitListenerContainerFactory")
    public void receiveD(Message message, Channel channel) throws IOException {
        System.out.println(" 当前时间:" + System.currentTimeMillis() + " 收到队列信息="
                + new String(message.getBody())
                + ",clientProperties=" + channel.getConnection().getClientProperties());
        MessageProperties messageProperties = message.getMessageProperties();
        try {
            //TODO 具体业务
            //表示成功确认，使用此回执方法后，消息会被rabbitmq broker 删除
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        } catch (Exception e) {
            if (message.getMessageProperties().getRedelivered()) {
                System.out.println("消息已重复处理失败,拒绝再次接收...");
                //拒绝消息，与basicNack区别在于不能进行批量操作，其他用法很相似
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false); // 拒绝消息
            } else {
                System.err.println("消息即将再次返回队列处理...");
                //表示失败确认，一般在消费消息业务异常时用到此方法，可以将消息重新投递入队列。
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }


}
